import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

type Book = {
  id: number;
  name: string;
  description: string;
  is_learning: boolean;
};

const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:8000';

const BookSelection: React.FC = () => {
  const [books, setBooks] = useState<Book[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchBooks = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          navigate('/login');
          return;
        }
        const response = await fetch(`${API_BASE}/books`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        const result = await response.json();

        if (result.code === 200) {
          setBooks(result.data);
        } else {
          setError(result.msg || "获取书本列表失败");
        }
      } catch (err) {
        console.error("获取书本列表失败:", err);
        setError("获取书本列表失败");
      } finally {
        setIsLoading(false);
      }
    };

    fetchBooks();
  }, [navigate]);

  const handleBookSelect = async (bookId: number) => {
    try {
      const response = await fetch(`${API_BASE}/books/${bookId}/start`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });
      
      const result = await response.json();
      
      if (result.code === 200) {
        // 开始学习成功，跳转到学习页面
        navigate('/study');
      } else if (result.code === 400) {
        // 已经在学习这本书，直接跳转到学习页面
        navigate('/study');
      } else if (result.code === 404 && result.msg === "这本书还没有单词") {
        // 如果这本书没有单词，显示提示框
        alert("这本书还没有单词");
      } else {
        setError(result.msg || '选择书本失败');
      }
    } catch (error) {
      console.error('选择书本失败:', error);
      setError('选择书本失败，请稍后再试');
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    navigate('/login');
  };

  if (isLoading) {
    return <div className="loading">加载书本列表...</div>;
  }

  if (error) {
    return <div className="error-message">{error}</div>;
  }

  if (books.length === 0) {
    return (
      <div className="book-selection-container">
        <p className="no-books-message">请联系管理员配置书本。</p>
      </div>
    );
  }

  return (
    <div className="book-selection-container">
      <button 
        className="logout-btn"
        onClick={handleLogout}
      >
        退出登录
      </button>
      <h2>选择要学习的书本</h2>
      {error && <div className="error-message">{error}</div>}
      <div className="book-list">
        {books.map((book) => (
          <div
            key={book.id}
            className={`book-card ${book.is_learning ? 'learning' : ''}`}
            onClick={() => handleBookSelect(book.id)}
          >
            <h3>{book.name}</h3>
            <p>{book.description}</p>
            {book.is_learning && <span className="learning-badge">学习中</span>}
          </div>
        ))}
      </div>
    </div>
  );
};

export default BookSelection; 